<?php
class UsersController extends DomController {
	
	public function users() {

		$this->view->contents = DomFg::render( $panel );
		
		$post = DomFgPost::getInstance('users')->store('users', array('search') );
		$query = User::query()->orderBy('t.username');
					
		if( $_GET['delete'] && $item = User::load( $_GET['delete'] )){
			$item->delete();
		}
		
		if( $post->search ) {
			$query->where('username LIKE \'%'.addslashes($post->search).'%\'');
		}

		function getName( $row ) {
			return $row->firstName.' '.$row->lastName;
		}
		
		function isActive( $row ) {
			if( $row->blocked ) {
				
				$toolTip = DomFgToolTip::c()
					->title('Blokeerimise põhjus')
					->contents($row->blockReason)
					->elementId( 'blockReason_'.$row->id);
				
				return '<b id="blockReason_'.$row->id.'" style="color:red">Blokeeritud</b>';
			} else if( !$row->emailConfirmed )
				return '<b style="color:orange">Kinnitamata</b>';
			else
				return '<b style="color:green">Ok</b>';
		}
		
		$panel = array(
			'title' => 'Kasutajad',
			'layout' => 'table',
			'layoutConfig' => array(
				'columns' => 4,
				'columnWidths' => array(150,60,220),
			),
			'action' => $this->getUrl('users/'),
			'items' => array(
				array(
					'type' => 'button',
					'title' => 'Lisa uus',
					'link' => $this->getUrl('user/'),
				),
				array(
					'type' => 'textField',
					'value' => $post->search,
					'name' => 'search',
					'title' => 'Otsi',
				),
				array(
					'type' => 'button',
					'title' => 'Otsi',
					'name' => 'doSearch',
				),
				array(
					'type' => 'grid',
					'name' => 'users',
					'pagerResetPostVar' => 'doSearch',
					'source' => new DomArDataSource( $query, 40, users ),
					'colspan' => 4,
					'fields' => array(
						array('key' => 'username', 'title' => 'Kasutajanimi'),
						array('handler'=>'getName', 'title' => 'Nimi'),
						array('key' => 'email', 'title' => 'Email'),
						array('handler' => 'isActive', 'title' => 'Aktiivne'),
						array('type' => 'gridButton', 'value' => 'Change', 'link' => $this->getUrl('user/'), 'title' => 'Valikud','colspan' => 2, 'width'=>50),
						array('type' => 'gridButton', 'value' => 'Delete', 'link' => $this->getUrl('users/&delete='), 'confirmMessage' => 'Are you sure?', 'width'=>50 ),
					),
				),
			),
		);
				
		$this->view->contents = DomFg::render( $panel );		
	}
	
	public function user( $id = NULL ) {

		$new = $id == 0;
		$item = $new ? new User() : User::load($id);
				
		$post = DomFgPost::getInstance();
		
		if( $post->save ) {
			
			$item->username = $post->username;
			if( $post->password1 )
				$item->password = array($post->password1,$post->password2);
			$item->email = $post->email;
			$item->emailConfirmed = (bool)$post->emailConfirmed;
			
			$item->firstName = $post->firstName;
			$item->lastName = $post->lastName;
			
			$item->blocked = (bool)$post->blocked;
			$item->blockReason = $post->blockReason;
			
			if( $item->save() ) {
				$id = $item->id;
				$message = array('type' => 'ok','colspan' => 2,'message' => 'Salvestatud',);
			} else {
				$message = array('message' => 'Tekkinud on viga!','type' => 'ok','colspan' => 2,'description' => implode('<br>',$item->getValidationReport()->messages),);
			}
		}

		$tabPanel = array(
			'type' => 'tabPanel',
			'headerTabs' => true,
			'action' => $this->getUrl('user/'.$id),
			'items' => array(
		
			),
		);
		
		// --------------------------------------------------------------
		$panel = array(
			'title' => 'Kasutaja',
			'layout' => 'table',
			'layoutConfig' => array(
				'columns' => 2,
				'columnWidths' => array( 150 ),
			),
			'items' => array(
				$message ,
				array(
					'type' => 'textField',
					'title' => 'Kasutajanimi',
					'value' => $item->username,
					'name' => 'username',
				),
				array(
					'type' => 'password',
					'title' => 'Parool',
					'name' => 'password1',
				),
				array(
					'type' => 'password',
					'title' => 'Parool uuesti',
					'name' => 'password2',
				),
				array(
					'type' => 'textField',
					'title' => 'Email',
					'value' => $item->email,
					'name' => 'email',
				),
				array(
					'type' => 'checkBox',
					'title' => 'Aktiveeritud',
					'checked' => $item->emailConfirmed,
					'name' => 'emailConfirmed',
					'textAfter' => '(Emaili aadress kinnitatud)',
				),
				
				array(
					'type' => 'separator',
					'title' => 'Isik',
					'colspan' => 2,
				),
				
				array(
					'type' => 'textField',
					'title' => 'Eesnimi',
					'value' => $item->firstName,
					'name' => 'firstName',
				),
				array(
					'type' => 'textField',
					'title' => 'Perenimi',
					'value' => $item->lastName,
					'name' => 'lastName',
				),
				
				array(
					'type' => 'separator',
					'title' => 'Blokeerimine',
					'colspan' => 2,
				),
				
				array(
					'type' => 'checkBox',
					'title' => 'Blokeeritud',
					'checked' => $item->blocked,
					'name' => 'blocked',
				),
				array(
					'type' => 'textField',
					'title' => 'Blokeerimise põhjus',
					'value' => $item->blockReason,
					'name' => 'blockReason',
					'width'=> '400px',
				),
				
				
				
			),
			'buttons' => array(
				array(
					'title' => 'Salvesta',
					'name' => 'save'
				),
			),
		);
		$tabPanel['items'][] = &$panel;

		// --------------------------------------------------------------
		
		if( $item->id > 0) {
			$statisticsPanel = array(
				'title' => 'Statistika',
				'layout' => 'table',
				'layoutConfig' => array(
					'columns' => 2,
					'columnWidths' => array( 150 ),
				),
				'items' => array(
					array(
						'type' => 'value',
						'title' => 'Registreerus',
						'value' => $item->registered->dateTime('d-m-Y H:i:s'),
					),
					array(
						'type' => 'value',
						'title' => 'Viimati logis sisse',
						'value' => $item->lastLogin->dateTime('d-m-Y H:i:s'),
					),
					array(
						'type' => 'value',
						'title' => 'Viimane tegevus',
						'value' => $item->lastAction->dateTime('d-m-Y H:i:s'),
					),
					
					array(
						'type' => 'value',
						'title' => 'Sisseloginud kordi',
						'value' => DomSql::selectOneQuery('SELECT count(*) as n FROM '.DomUserActionLog::getDbTable().' WHERE user = '.$item->id.' AND userClassName = \''.get_class($item).'\' AND action = 1','n'),
					),
				),
			);
			$tabPanel['items'][] = &$statisticsPanel;
		}
		// --------------------------------------------------------------
		
		if( $item->id > 0) {
			$time = 60;
			if( $post->findRelatedUsers ) {
				$data = DomSql::selectQuery('
					SELECT u.id, u.username, count(DISTINCT x.id) as n
					FROM '.DomUserActionLog::getDbTable().' as l
					JOIN '.DomUserActionLog::getDbTable().' as x ON (l.ip = x.ip )
					LEFT JOIN '.$item->getDbTable().' as u ON (x.user = u.id)
					WHERE 
						l.user = '.$item->id.' 
						AND l.userClassName = \''.get_class($item).'\' 
						AND l.date >= \''.date('Y-m-d H:i:s',strtotime('-'.$time.' days')).'\'
						AND l.action = 2
						AND x.user != l.user
						AND x.date >= \''.date('Y-m-d H:i:s',strtotime('-'.$time.' days')).'\'
						AND x.action = 2
					GROUP BY x.user
				')->toArray();
			}
			$loggedInTimes = DomSql::selectOneQuery('
					SELECT count(*) as n 
					FROM '.DomUserActionLog::getDbTable().' as l
					WHERE l.user = '.$item->id.' 
					AND l.userClassName = \''.get_class($item).'\' 
					AND l.date >= \''.date('Y-m-d H:i:s',strtotime('-'.$time.' days')).'\'
					AND l.action = 2
			','n');
			
			$similarPanel = array(
				'title' => 'Sarnased',
				'layout' => 'table',
				'layoutConfig' => array(
					'columns' => 2,
					'columnWidths' => array( 150 ),
				),
				'items' => array(
					array(
						'colspan' => 2,
						'type' => 'info',
						'message' => 'Tähelepanu!',
						'description' => 'Siin listis olevad kasutajad ei pea tingimata olema '.$user->username.' alternatiiv kasutajad. Kui kaks kasutajat on ühes kontoris siis meile tundub, et nad oleks nagu sama inimene.',
					),
					array(
						'type' => 'value',	
						'title' => 'Kasutajanimi',
						'value' => '<b>'.$item->username.'</b>',
					),
					array(
						'type' => 'value',	
						'title' => 'Sisselogimisi',
						'value' => '<b>'.$loggedInTimes.'</b>',
					),
					array('type' => 'value'),
					array(
						'type' => 'button',
						'name' => 'findRelatedUsers',
						'title' => 'Otsi',
					),
					( $post->findRelatedUsers ? array(
						'colspan' => 2,
						'type' => 'grid',
						'source' => new DomFgDataSource( $data, 100 ),
						'fields' => array(
							array('key' => 'username', 'title' => 'Teine kasutajanimi'),
							array('key' => 'n', 'title' => 'Samalt IP-lt sisselogimisi'),
							array('type' => 'gridButton', 'value'=> 'Vaata kasutajat','link' => $this->getUrl('user/'), 'title' => 'Valikud'),
						),
					) : NULL ),
				),
			);
			$tabPanel['items'][] = &$similarPanel;
		}
			
		// --------------------------------------------------------------
		
		$this->view->contents = DomFg::render( $tabPanel );
		
	}
		
		public function statistics( ) {

		$userClassname = 'AdminUser';
		$logInsByDate = DomSql::keyListQuery('SELECT DATE(date) as d, count(*) as logins  FROM '.DomUserActionLog::getDbTable().' WHERE userClassName=\''.$userClassname.'\' AND action = 2 GROUP BY d ORDER BY d DESC LIMIT 60 ','d','logins')->toArray();
		$registrationsByDate = DomSql::keyListQuery('SELECT DATE(registered) as d, count(*) as registrations FROM '.AdminUser::getDbTable().' GROUP BY d ORDER BY d DESC LIMIT 60','d','registrations')->toArray();	
		$maxLogIns = max($logInsByDate);
		$maxRegistrations = max($registrationsByDate);
		
		$statistics = array();
		$period = new DomDateTimePeriod(strtotime('-60 days'),'now');
		foreach( $period->getDays() as $dayPeriod ) {
			$dayDate = $dayPeriod->getStart()->date('Y-m-d');
			$statistics[$dayDate] = array(
				'date' => $dayDate,
				'logins' => $logInsByDate[$dayDate],
				'registrations' => $registrationsByDate[$dayDate],
			);
		}
		$statistics = array_reverse($statistics);

		function bar( $value, $row, $i, $max ) {	
			$width = round($value * 200 / $max);
			return '<div style="background-color:blue; width:'.$width.'px; height:6px;"></div>';
		}
		
		$panel = array(
			'title' => 'Statistika',
			'layout' => 'table',
			'action' => $this->getUrl('statistics/'.$id),
			'layoutConfig' => array(
				'columns' => 2,
				'columnWidths' => array( 250 ),
			),
			'items' => array(
				$message ,
				array(
					'type' => 'value',
					'title' => 'Kasutajaid kokku',
					'value' => DomSql::selectOneQuery('SELECT count(*) as n FROM '.AdminUser::getDbTable().' as u','n'),
				),
				array(
					'type' => 'value',
					'title' => 'Aktiivseid kasutajaid kokku',
					'value' => DomSql::selectOneQuery('SELECT count(*) as n FROM '.AdminUser::getDbTable().' as u WHERE emailConfirmed = 1 AND blocked != 1','n'),
				),
				array(
					'type' => 'value',
					'title' => 'Blokeeritud kasutajaid kokku',
					'value' => DomSql::selectOneQuery('SELECT count(*) as n FROM '.AdminUser::getDbTable().' as u WHERE blocked = 1','n'),
				),
				array(
					'colspan' => 2,
					'type' => 'grid',
					'source' => new DomFgDataSource( $statistics, 1000 ),
					'fields' => array(
						array('key' => 'date', 'title' => 'Kuupäev', 'width'=>80,),
						array('key' => 'logins', 'title' => 'Sisselogimisi', 'width' => 50, 'colspan' => 2,),
						array('handler' => 'bar', 'key' =>'logins', 'handlerArgs' => array($maxLogIns), 'width' => 100),
						array('key' => 'registrations', 'title' => 'Registreerimisi', 'width' => 50, 'colspan' => 2,),
						array('handler' => 'bar', 'key' =>'registrations', 'handlerArgs' => array($maxRegistrations), 'width' => 100),
					),
				),
			),
		);
				
		$this->view->contents = DomFg::render( $panel );
		
	}
	
	
	public function _prepareLogin() {
		$post = DomFgPost::getInstance();
		if( $post->login ) {
			
			$result = User::loginByUsername( $_REQUEST['username'], $_REQUEST['password'] );
			
			if( 0 === $result ) {
				$this->goToUrl( $_SERVER['HTTP_REFERER'] );
			} else if( 100 == $result ) {
				$errorMessage = 'Kasutajat ei leitud';
			} else if( 101 == $result) {
				$errorMessage = 'Parool ei ole õige!';
			} else if( 1 == $result) {
				$errorMessage = 'Kasutaja ei ole aktiveeritud';
			} else if( 2 == $result) {
				$errorMessage = 'Kasutaja on blokeeritud!';
			} else {
				$errorMessage = 'Tundmatu viga nr ' . $result . '!';
			}
			
			$error = array(
				'type' => 'error',
				'message' => $errorMessage,
				'colspan' => 2,
			);
		}
		
		
		$panel = array(
			'title' => 'Administratsioon',
			'layout' => 'table',
			'layoutConfig' => array(
				'columns' => 2,
			),
			'style' => 'width:470px',
			'action' => $this->getCurrentUrl(),
			'items' => array(
				$error,
				array(
					'type' => 'textField',
					'title' => 'Kasutajanimi',
					'name' => 'username',
					'value' => $post->username,
				),
				array(
					'type' => 'password',
					'title' => 'Parool',
					'name' => 'password',				
				),
				array('type' => 'value',),
				array(
					'type' => 'button',
					'title' => 'Logi sisse',
					'name' => 'login',
				),
			),
		);
		
		
		$this->view->contents = DomFg::render( $panel );
	}
	
	public function _prepareloggedIn() {
		if( $_GET['logout'] ) {
			$this->getUser()->logout();
			$this->goTo( $this->getSiteUrl() );
		}
		
		$menu = array(
			'type' => 'menu',
			'items' => array(
				array(
					'title' => 'Kasutajad',	
					'link' => $this->getUrl('users/'),
					'items' => array(
						array(
							'title' => 'Kasutajad',
							'link' => $this->getUrl('users/'),
						),
						array(
							'title' => 'Statistika',
							'link' => $this->getUrl('statistics/'),
						),
					),
				),
				array(
					'title' => 'Logi välja',
					'link' => $this->getSiteUrl('?logout=1'),
				),
			),
		);
	
		$this->view->menu = DomFg::render( $menu );
	}
	
	public function error404() {
		$this->view->addPartitioner('contents', 'Errors/error404.html');
	}
	
	public function error403() {
		$panel = array(
			'style' => 'width:470px',
			'type' => 'panel',
			'items' => array(
				array(
					'type' => 'warning',
					'message' => 'Antud lehe nägemiseks peate sisselogima!',
				),
			),
		);
		$this->view->addPartitioner('contents', 'Errors/error403.html');
		$this->view->error403 = DomFg::render( $panel );
		$this->_prepareLogin();
	}
	
	public function setup() {
		if( $user = User::getLoggedInUser() ) {
			$this->getSite()->setUser( $user );
			$this->_prepareloggedIn();
		} else {
			
			$location = $this->getSite()->getLocation();
			if( $location['controller'] != 'users' or $location['controller'] == 'users' && $location['method'] != 'index')
				$this->auth();

			$this->_prepareLogin();
		}
	}
}
?>